package com.yy.permissions_general.security;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yy.permissions_general.module.system.menu.mapper.AuthMapper;
import com.yy.permissions_general.module.system.menu.vo.MenuVo;
import com.yy.permissions_general.module.system.role.entity.Role;
import com.yy.permissions_general.module.system.role.mapper.RoleMapper;
import com.yy.permissions_general.module.system.user.entity.User;
import com.yy.permissions_general.module.system.user.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description:用戶信息
 * @Author: YY
 * @Date: 2021/11/2
 */
@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private AuthMapper authMapper;

    @Override
    public User loadUserByUsername(String account) {
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("account",account));
        if (user == null) {
            throw new BadCredentialsException("用户名或密码错误~");
        } else if (user.getStatus().equals("1")) {
            throw new LockedException("用户被锁定,请联系管理员解锁~");
        }
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        List<MenuVo> list = authMapper.selectMenuVoByUser(user);
        List<String> collect = list.stream().map(MenuVo::getAuthCode).collect(Collectors.toList());
        for (String authority : collect) {
            if (StringUtils.isNotBlank(authority)) {
                GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(authority);
                grantedAuthorities.add(grantedAuthority);
            }
        }
        //将用户所拥有的权限加入GrantedAuthority集合中
        user.setLastTime(new Date());
        userMapper.updateById(user);
        user.setMenuVoList(list);
        return user;
    }

    /**
     * 获取用户角色
     *
     * @param user
     * @return
     */
    public List<Role> getRoleInfo(User user) {
        return roleMapper.selectRoleByUser(user);
    }

}